package com.mzj.saas.mservice.sys.service;

import com.mzj.saas.commons.ApiData;
import com.mzj.saas.commons.ResultBean;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.sys.entity.BacklogItemMessageUser;
import com.mzj.saas.mservice.sys.repository.BacklogItemMessageUserRepository;
import com.mzj.saas.mservice.sys.vo.MessageTypeVo;
import com.mzj.saas.mservice.sys.vo.MessageUserVo;
import com.mzj.saas.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MessageUserService {
    private static final Logger LOG = LoggerFactory.getLogger(MessageUserService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private BacklogItemMessageUserRepository backlogItemMessageUserRepository;

    /**
     * 列表
     * @param accessToken
     * @param pageNumber
     * @param pageSize
     * @return
     */
    public ResultBean<Object> list(String accessToken, Integer pageNumber, Integer pageSize) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            Long enterpriseId = tokenRedisVo.getEnterpriseId();

            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }

            ApiData<MessageUserVo> apiData = new ApiData<>();

            String sql = " SELECT a.id,a.user_id AS userId,b.name as name,a.type as type FROM saas_backlog_item_message_user a INNER JOIN saas_user b ON a.user_id=b.id  WHERE a.org_id=?  GROUP BY user_id  \n";

            String offsets = "  LIMIT ? OFFSET ? ";
            String count = "SELECT COUNT(0) FROM (" + sql + ") c";
            List<Object> args = new ArrayList<>();
            args.add(tokenRedisVo.getEnterpriseId());
            // 查询总记录数
            Long total = jdbcTemplate.queryForObject(count, args.toArray(), Long.class);
            if (total == 0) {
                return ResultBean.successfulResult(apiData);
            }

            // 查询分页数据
            sql += offsets;
            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<MessageUserVo> peopleList = jdbcTemplate.query(sql, new BeanPropertyRowMapper(MessageUserVo.class), args.toArray());
            //实现把消息类型放成集合返回给前端
            for (MessageUserVo messageUserVo : peopleList) {
                String userId = messageUserVo.getUserId();
                ArrayList<Integer> typeList = new ArrayList<>();
                List<BacklogItemMessageUser> byUserId = backlogItemMessageUserRepository.findByUserId(userId);
                if (!byUserId.isEmpty()) {
                    for (BacklogItemMessageUser backlogItemMessageUser : byUserId) {
                        Integer type = backlogItemMessageUser.getType();
                        typeList.add(type);
                    }
                    messageUserVo.setTypeList(typeList);
                }
            }
            apiData.setData(peopleList);
            apiData.setTotal(total);
            return ResultBean.successfulResult(apiData);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 添加
     * @param accessToken
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Object> save(String accessToken, String userId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            Long enterpriseId = tokenRedisVo.getEnterpriseId();

            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }
            ArrayList<BacklogItemMessageUser> list = new ArrayList<>();

                BacklogItemMessageUser userIdAndOrgId = backlogItemMessageUserRepository.findByUserIdAndOrgId(userId, enterpriseId);
                if (userIdAndOrgId != null ){
                    return ResultBean.failedResultWithMsg("该推送人已被添加");
                }
                BacklogItemMessageUser messageUser = new BacklogItemMessageUser();
                messageUser.setOrgId(enterpriseId);//机构id
                messageUser.setAreaId(hierarchy.getAreaId());//区域id
                messageUser.setUserId(userId);//接收用户id
                messageUser.setOperatorId(tokenRedisVo.getId());//操作人iD
                messageUser.setOperatorTime(new Date());//操作时间

                list.add(messageUser);



            backlogItemMessageUserRepository.saveAll(list);


            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 删除
     * @param accessToken
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Object> delete(String accessToken, String userId) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            List<BacklogItemMessageUser> messageUser = backlogItemMessageUserRepository.findByUserId(userId);
            if (!messageUser.isEmpty()) {
                for (BacklogItemMessageUser backlogItemMessageUser : messageUser) {
                    Long id = backlogItemMessageUser.getId();
                    backlogItemMessageUserRepository.deleteById(id);
                }
            } else {
                return ResultBean.failedResultWithMsg("推送人信息不存在或是已删除");
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /*
     *新增推送人员,可选择推送内容
     */
    public ResultBean<Object> saveType(String accessToken, MessageTypeVo messageTypeVo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            Long enterpriseId = tokenRedisVo.getEnterpriseId();
            String userId = messageTypeVo.getUserId();
            List<Integer> typeList = messageTypeVo.getTypeList();
            if (userId == null) {
                return ResultBean.failedResultWithMsg("请添加推送人员");
            }
            if (typeList.isEmpty()) {
                return ResultBean.failedResultWithMsg("请选择推送类型");
            }
            DepartmentHierarchy hierarchy = departmentHierarchyRepository.findByOrgIdAndStatus(enterpriseId, 1);
            if (hierarchy == null) {
                return ResultBean.failedResultWithMsg("用户所属机构未设置层级架构");
            }

            ArrayList<BacklogItemMessageUser> list = new ArrayList<>();
            for (Integer integer : typeList) {
                BacklogItemMessageUser userIdAndOrgId = backlogItemMessageUserRepository.findByUserIdAndOrgIdAndType(userId, enterpriseId,integer);
                if (userIdAndOrgId != null ){
                    userIdAndOrgId.setOrgId(enterpriseId);//机构id
                    userIdAndOrgId.setAreaId(hierarchy.getAreaId());//区域id
                    userIdAndOrgId.setUserId(userId);//接收用户id
                    userIdAndOrgId.setOperatorId(tokenRedisVo.getId());//操作人iD
                    userIdAndOrgId.setOperatorTime(new Date());//操作时间
                    userIdAndOrgId.setType(integer);//推送类型
                    list.add(userIdAndOrgId);
                } else {
                    BacklogItemMessageUser messageUser = new BacklogItemMessageUser();
                    messageUser.setOrgId(enterpriseId);//机构id
                    messageUser.setAreaId(hierarchy.getAreaId());//区域id
                    messageUser.setUserId(userId);//接收用户id
                    messageUser.setOperatorId(tokenRedisVo.getId());//操作人iD
                    messageUser.setOperatorTime(new Date());//操作时间
                    messageUser.setType(integer);//推送类型
                    list.add(messageUser);
                }
            }
            backlogItemMessageUserRepository.saveAll(list);

            return ResultBean.successfulResult("设置成功");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }
}

